/*
 * Copyright 2009 Kaspar Minosiants http://www.minosiants.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.minosiants.confluence.blog.plugin.impl.tweet2it;


import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;

import com.atlassian.bandana.BandanaManager;
import com.atlassian.confluence.setup.bandana.ConfluenceBandanaContext;
import com.atlassian.spring.container.ContainerManager;
import com.minosiants.confluence.blog.plugin.tweet2it.IContextUtil;
import com.minosiants.confluence.blog.plugin.tweet2it.IDataReopository;
import com.thoughtworks.xstream.XStream;

/**
 *	Project home: http://tweet2it.minosiants.com
 *
 *  @author Kaspar Minosiants
 *
 * 	$Id:$
 */
public class ConfluenceDataReopository implements IDataReopository{
	private Log logger = LogFactory.getLog(getClass());
	private Map<String,OAuthUserData> oauthUsersDataMap;
	private XStream xstream;
	private BandanaManager bandanaManager;
	
	@Override
	public synchronized void storeOAuthUserData(String id, OAuthUserData oauthUserData) {
		logger.info("storeOAuthUserData id: "+id);
		getOauthUsersDataMap().put(id, oauthUserData);		
		updateBandanaContext();			
	}
	@Override
	public OAuthUserData getOAuthUserData(String id) {
		logger.debug("getOAuthUserData id: "+id);
		return getOauthUsersDataMap().get(id);
	}
	@Override
	public synchronized void removeOAuthUserData(String id) {
		if(getOauthUsersDataMap().remove(id)!=null)
			updateBandanaContext();		
	}	
	private void updateBandanaContext() {
		TransactionTemplate tt = new TransactionTemplate();
		tt.setTransactionManager((PlatformTransactionManager) ContainerManager.getInstance().getContainerContext().getComponent("transactionManager"));				
		tt.execute(new TransactionCallbackWithoutResult() {
		   protected void doInTransactionWithoutResult(TransactionStatus status) {
				String xml=getXStream().toXML(oauthUsersDataMap);
				bandanaManager.setValue(new ConfluenceBandanaContext(), IContextUtil.Constants.BANDANA_CTX_KEY_TWITTER_USERS, xml);			   
		   }
		 }
		);
	}
	public void setBandanaManager(BandanaManager bandanaManager) {
		this.bandanaManager = bandanaManager;
	}
	
	private XStream getXStream(){
		if(xstream == null){
			xstream = new XStream();
			xstream.setClassLoader(getClass().getClassLoader());
		}		
		return xstream;
	}
	private Map<String,OAuthUserData> createOauthUsersData(){
		String xml= (String) bandanaManager.getValue(new ConfluenceBandanaContext(), IContextUtil.Constants.BANDANA_CTX_KEY_TWITTER_USERS);		
		oauthUsersDataMap =hasData(xml) ? (Map<String,OAuthUserData>)getXStream().fromXML(xml) : new HashMap<String, OAuthUserData>();
		return oauthUsersDataMap;  
	}
	private boolean hasData(String xml){
		return !"<null/>".equals(xml) && StringUtils.hasText(xml) ; 
	}
	private Map<String, OAuthUserData> getOauthUsersDataMap() {
		if(bandanaManager==null)
			ContainerManager.autowireComponent(this);		
		logger.info("oauthUsersDataMap: "+oauthUsersDataMap);
		return oauthUsersDataMap !=null ? oauthUsersDataMap :createOauthUsersData();
	}

	
}
